package com.health.mapp.interImpl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.health.db.dto.StuffDetailDto;
import com.health.db.model.EPayCashPayment;
import com.health.db.model.EPayCashPaymentExample;
import com.health.db.model.GoodsOrder;
import com.health.db.model.GoodsOrderContact;
import com.health.db.model.RegisterOrder;
import com.health.db.model.SubRegisterOrder;
import com.health.db.model.UserAccountLedger;
import com.health.db.model.UserLIST;
import com.health.db.service.order.IEPayCashPaymentService;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.order.ISubRegisterOrderService;
import com.health.db.service.sm.IAlipayService;
import com.health.db.service.sm.IGoodsDataService;
import com.health.db.service.sm.IGoodsOrderContactService;
import com.health.db.service.sm.IGoodsOrderService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.ISMSSendService;
import com.health.db.service.sm.IWXPayService;
import com.health.db.service.user.ICourseShareLedgerService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserAccountLedgerService;
import com.health.db.service.user.IUserCardListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.service.SpringContextUtil;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.PropertiesUtil;
import com.health.pay.tencent.protocol.closeorder.CloseOrderReqData;
import com.health.pay.tencent.protocol.refund.RefundReqData;
import com.health.pay.tencent.protocol.refund.RefundResData;
/**
 * 微信和支付宝付费操作-订单后续操作类
 * 具体实现内容为：将等待支付订单修改为等待就诊状态
 * 不涉及医生账户的操作，因为此时钱还在第三方账户中
 * 
 * @author acer
 *
 */
public class PayActionServerImpl  {

	private static Logger logger = Logger.getLogger(PayActionServerImpl.class);
	

	/**
	 * 
	 * 商户订单号 支付方式 账单类型
	 * 不同的订单有着不同的结尾   
	 * @param out_trade_no
	 * @param payTypeId
	 * @param CONSTANTS_VOUCHERNAME
	 * @throws Exception
	 * @throws
	 */
	public void payAction(String out_trade_no, short payTypeId)
			throws Exception {
		// 会员回调  -51
		if (out_trade_no.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_51.toString()))) {
			goodsOrderVIPPayAction(out_trade_no, payTypeId);
		}
		// 充值回调  -41
		else if (out_trade_no.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_41.toString()))) {
			goodsOrderPayAction(out_trade_no, payTypeId);
		// 买卡回调 -42
		} else if (out_trade_no.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_42.toString()))) {
			cardOrderOrderPayAction(out_trade_no, payTypeId);
		// 子订单回调 -43
		} else if (out_trade_no.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_43.toString()))) {
			subRegisterOrderOrderPayAction(out_trade_no, payTypeId);
		// 咨询订单回调 -61
		} else if (out_trade_no.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_61.toString()))) {
			courseOrderOrderPayAction(out_trade_no, payTypeId);
		// 咨询订单回调 	
		} else {
			registerOrderPayAction(out_trade_no, payTypeId);
		}
	}
	
	/**
	 * 课程 回调  -暂未支持
	 * @param out_trade_no
	 * @param payTypeId
	 * @throws Exception
	 */
	public void courseOrderOrderPayAction(String out_trade_no ,short payTypeId) throws Exception {
		
		//最近版本无
		IGoodsOrderService goodsOrderService = SpringContextUtil.getBean("goodsOrderService");
		
		String[] strs = out_trade_no.split("-");
		
		GoodsOrder currGoodsOrder = goodsOrderService.selectByPrimaryKey(Long.valueOf(strs[1]));
		
		if(currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1.intValue()){
			
			currGoodsOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			currGoodsOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
			//是否支付
			currGoodsOrder.setPayFlag(String.valueOf(Constant.CONSTANTS_IS_PAYMENT_TRUE));
			//支付方式
			currGoodsOrder.setPayTypeId(payTypeId);
			goodsOrderService.updateOrder4Payment(currGoodsOrder, out_trade_no);
			
			ICourseShareLedgerService courseShareLedgerService = SpringContextUtil.getBean("courseShareLedgerService");
			courseShareLedgerService.updateCourseShareLedgePayment(currGoodsOrder, out_trade_no);
			
			IGoodsOrderContactService goodsOrderContactService =  SpringContextUtil.getBean("goodsOrderContactService");
			
			GoodsOrderContact goodsOrderContact = new GoodsOrderContact();
			goodsOrderContact.setOrderId(currGoodsOrder.getRecid());
			goodsOrderContact.setStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			goodsOrderContact.setStatusId(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5.shortValue());
			goodsOrderContactService.updateStatusByOrderId(goodsOrderContact);
			
		}else if (currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5.intValue()) {
			//退款
			cancelPayment(out_trade_no);
		}
	}

	
	/**
	 * 买卡 回调  -暂未支持
	 * @param out_trade_no
	 * @param payTypeId
	 * @throws Exception
	 */
	public void cardOrderOrderPayAction(String out_trade_no ,short payTypeId) throws Exception {
		
	}

	
	/**
	 * 子订单回调
	 * @param out_trade_no
	 * @param payTypeId
	 */
	public void subRegisterOrderOrderPayAction(String out_trade_no ,short payTypeId) throws Exception {
		
		ISubRegisterOrderService subRegisterOrderService = SpringContextUtil.getBean("subRegisterOrderService");
		
		String[] strs = out_trade_no.split("-");
		
		SubRegisterOrder currGoodsOrder = subRegisterOrderService.selectByPrimaryKey(Long.valueOf(strs[1]));
		
		if(currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1.intValue()){
			
			//currGoodsOrder.setGoodsid(Long.valueOf(strs[1]));
			currGoodsOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			currGoodsOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
			
			//是否支付
			currGoodsOrder.setRegisterPayFlag(Constant.CONSTANTS_IS_PAYMENT_TRUE);
			//支付方式
			currGoodsOrder.setPaytypeid(payTypeId);
			
			subRegisterOrderService.updateOrder4Payment(currGoodsOrder, out_trade_no);
			
		}else if (currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5.intValue()) {
			//退款
			cancelPayment(out_trade_no);
		}
	}
	
	
	/**
	 * 会员商品 VIP
	 * @param out_trade_no
	 * @param payTypeId
	 */
	public void goodsOrderVIPPayAction(String out_trade_no ,short payTypeId) throws Exception {
		
		IGoodsOrderService goodsOrderService = SpringContextUtil.getBean("goodsOrderService");
		IGoodsDataService goodsDataService = SpringContextUtil.getBean("goodsDataService");
		String[] strs = out_trade_no.split("-");
		GoodsOrder currGoodsOrder = goodsOrderService.selectByPrimaryKey(Long.valueOf(strs[1]));
		
		if(currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1.intValue()){
			
			currGoodsOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			currGoodsOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
			//是否支付
			currGoodsOrder.setPayFlag(String.valueOf(Constant.CONSTANTS_IS_PAYMENT_TRUE));
			//支付方式
			currGoodsOrder.setPayTypeId(payTypeId);
			
			String goodsType = currGoodsOrder.getGoodsType();
			
			if (StringUtils.isNotBlank(goodsType)&&
					(Integer.valueOf(goodsType).intValue()==Constant.CONSTANTS_PAY_ACTION_ID_51.intValue())) {
				
				goodsDataService.insertVIPGoodsList(currGoodsOrder, out_trade_no);
			}
		}else if (currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5.intValue()) {
			//退款
			cancelPayment(out_trade_no);
		}
	}
	
	
	/**
	 * 
	 * @param out_trade_no
	 * @param payTypeId
	 */
	public void goodsOrderPayAction(String out_trade_no ,short payTypeId) throws Exception {
		
		//最近版本无
		//IUserAccountLedgerService userAccountLedgerService = SpringContextUtil.getBean("userAccountLedgerService");
		IGoodsOrderService goodsOrderService = SpringContextUtil.getBean("goodsOrderService");
		IUserCardListService userCardListService = SpringContextUtil.getBean("userCardListService");
		
		String[] strs = out_trade_no.split("-");
		
		GoodsOrder currGoodsOrder = goodsOrderService.selectByPrimaryKey(Long.valueOf(strs[1]));
		
		if(currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1.intValue()){
			
			//currGoodsOrder.setGoodsid(Long.valueOf(strs[1]));
			currGoodsOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
			currGoodsOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
			
			//是否支付
			currGoodsOrder.setPayFlag(String.valueOf(Constant.CONSTANTS_IS_PAYMENT_TRUE));
			//支付方式
			currGoodsOrder.setPayTypeId(payTypeId);
			Long userId =currGoodsOrder.getOwnerid();
			
			userCardListService.activeUserCardByRecharge(userId, currGoodsOrder.getGoodsid());
			//充值金额现在写入卡
//			UserAccountLedger accountLedge = userAccountLedgerService.selectByUserId(userId);
//			int accountType=0;
//			if (null!=accountLedge) {
//				accountType=1;
//				accountLedge.setBalanceTotal(accountLedge.getBalanceTotal().add(currGoodsOrder.getTotal()));
//				
//				//增加赠送金额
//				if (null!=currGoodsOrder.getGiftAmount()) {
//					//余额
//					accountLedge.setBalanceTotal(accountLedge.getBalanceTotal().add(currGoodsOrder.getGiftAmount()));
//					//赠送总额
//					accountLedge.setBalanceAmount(accountLedge.getBalanceAmount().add(currGoodsOrder.getGiftAmount()));
//					//最后一次赠送额度
//					accountLedge.setBalanceQuantity(currGoodsOrder.getGiftAmount());
//				}
//			}
//			else{
//				accountLedge = new UserAccountLedger();
//				
//				accountLedge.setBalanceTotal(currGoodsOrder.getTotal());
//				
//				if (null!=currGoodsOrder.getGiftAmount()) {
//					accountLedge.setBalanceTotal(accountLedge.getBalanceTotal().add(currGoodsOrder.getGiftAmount()));
//					//赠送总额
//					accountLedge.setBalanceAmount(currGoodsOrder.getGiftAmount());
//					//最后一次赠送额度
//					accountLedge.setBalanceQuantity(currGoodsOrder.getGiftAmount());
//				}
//				
//				accountLedge.setAccountid(userId);
//				accountLedge.setIsUsedFlag((short) 1);
//				accountLedge.setColumnid(2);
//			}
			goodsOrderService.updateOrder4Payment(currGoodsOrder, out_trade_no);
			
		}else if (currGoodsOrder.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5.intValue()) {
			//退款
			cancelPayment(out_trade_no);
		}
	}
	
	
	/**
	 * 
	 * @param out_trade_no
	 * @param payTypeId
	 */
	public void registerOrderPayAction(String out_trade_no ,short payTypeId) throws Exception {
		IRegisterOrderService registerOrderService =	SpringContextUtil.getBean("registerOrderService");
		IUserLISTService userLISTService = SpringContextUtil.getBean("userLISTService");
		IUserAccountLedgerService userAccountLedgerService = SpringContextUtil.getBean("userAccountLedgerService");
		IRongService rongService  = SpringContextUtil.getBean("rongService");
		ISMSSendService sMSSendService  = SpringContextUtil.getBean("sMSSendService");
		IStuffListService stuffListService =  SpringContextUtil.getBean("stuffListService");
		
		String[] strs = out_trade_no.split("-");
		
		RegisterOrder  currOrderInfo  =registerOrderService.selectSimpleSingleByOrderId(Long.valueOf(Long.valueOf(Long.valueOf(strs[1]))));
		
		//正常的订单
		if(currOrderInfo.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1.intValue()){
			
			currOrderInfo.setRegisterid(Long.valueOf(Long.valueOf(strs[1])));
			currOrderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
			currOrderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
			//currOrderInfo.setRegisterPayFlag((short) 1);
			//是否支付
			currOrderInfo.setRegisterPayFlag(Constant.CONSTANTS_IS_PAYMENT_TRUE);
			//支付方式
			currOrderInfo.setPayTypeId(payTypeId);
			
			Long userId = currOrderInfo.getUserid();
			
			//用户账户表
			UserAccountLedger accountLedge = userAccountLedgerService.selectByUserId(userId);
			int accountType=0;
			if (null!=accountLedge) {
				accountType=1;
				//accountLedge.setBalanceAmount(accountLedge.getBalanceTotal());
			}
			else{
				accountLedge = new UserAccountLedger();
				accountLedge.setBalanceTotal(new BigDecimal("0"));
				accountLedge.setAccountid(userId);
				accountLedge.setIsUsedFlag((short) 1);
				accountLedge.setColumnid(2);
			}
			
			//更新订单表，并写日志
			registerOrderService.updateOrder4Payment(currOrderInfo,accountLedge,accountType,out_trade_no);
			
			String groupId = String.valueOf(currOrderInfo.getRegisterid() );
			String[] userIds = {String.valueOf(userId)};
			rongService.createGroup(userIds, groupId, groupId);
			rongService.PublishSystemOrderToDocMsg(currOrderInfo);
			
			//判断是否有客服 ssMeasure 医助编号
			if (StringUtils.isNotEmpty(currOrderInfo.getSsMeasure())) {
				String[] assisIds = {currOrderInfo.getSsMeasure()};
				rongService.joinGroup(assisIds, groupId, groupId);
				rongService.PublishSystemOrderToAssisMsg(String.valueOf(userId),currOrderInfo.getSsMeasure(), groupId);
				
			}
			/*if (null!=currOrderInfo.getAccepterid()) {
				StuffDetailDto stuffDetail = stuffListService. selectByStuffId(currOrderInfo.getAccepterid());
				
				if (null!=stuffDetail&&null!=stuffDetail.getStuffAlias()) {
					//客服加入群组
					String[] assisIds = {String.valueOf(stuffDetail.getStuffAlias())};
					rongService.joinGroup(assisIds, groupId, groupId);
					rongService.PublishSystemOrderToAssisMsg(String.valueOf(userId), stuffDetail.getStuffAlias(), groupId);
				}
			}*/
			
			//视屏咨询
			if (currOrderInfo.getRegistertypeid().intValue()!=Constant.CONSTANTS_ORDER_TYPE_ID_1.intValue()) {
				//SendSMS(currRegisterOrder);
				UserLIST docUser = userLISTService.selectByUserId(currOrderInfo.getAccepterid());
				sMSSendService.noticeOrder(docUser, currOrderInfo);
			}
			
			/**
			 * 第三方登录需要回调
			 */
			String appId = currOrderInfo.getWorkFlowStatus();
			if (StringUtils.isNotBlank(appId)&&appId.equals(Constant.PARTNER_APPID)) {
				callPartner(strs[0],String.valueOf(currOrderInfo.getRegisterTotal().setScale(2, BigDecimal.ROUND_HALF_UP)),currOrderInfo.getUserid());
			}
			
		}else if (currOrderInfo.getRunstatusid().intValue()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5.intValue()) {
			//退款
			cancelPayment(out_trade_no);
		}
	}
	
	

	/**
	 * 
	 * 第三方生成的订单
	 */
	
	private void callPartner(String payCashId,String payOffTotal,Long userId){
		
		ThirdInterface iface = new ThirdInterface();
		
		iface.payRecord(payCashId, payOffTotal, "0", userId);
	}
	
	/**
	 * 	 日志塞入
	 * @param ePayCashPayment
	 * @return payCashId
	 */
	public Long insertPayCashPaymentLog(String  orderId ,Short flag,IEPayCashPaymentService ePayCashPaymentService ) {
		
		EPayCashPayment payment = new EPayCashPayment();
		
		payment.setCreateDate(new Date());
		payment.setPaycashIdno("-"+String.valueOf(orderId));
		payment.setPaystepid(Constant.CONSTANTS_PAY_STEP_1);
		payment.setPaycashSign(Constant.CONSTANTS_IS_PAYMENT_FALSE);
		payment.setPaycashTypeid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WEIXIN));
		
		payment.setCreateUserid(PropertiesUtil.getLong("defalutUser",2));
		payment.setUpdateUserid(PropertiesUtil.getLong("defalutUser",2));
		payment.setRunStatus(String.valueOf(Constant.CONSTANTS_PAY_STATUS_NORMAL));
		
		if(flag.shortValue()==Constant.CONSTANTS_PAYMENT_WEIXIN){
			payment.setPaycashTypeid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WEIXIN));
			payment.setPaycashTypeName(Constant.CONSTANTS_VOUCHERNAME_2);
		}else if(flag.shortValue()==Constant.CONSTANTS_PAYMENT_ALIPAY){
			payment.setPaycashTypeid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_ALIPAY));
			payment.setPaycashTypeName(Constant.CONSTANTS_VOUCHERNAME_4);
		}
		
		//订单种类以及来源方式
		if (orderId.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_41.toString()))) {
			payment.setVoucherid(orderId.substring(0,orderId.length()-3));
			payment.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_41);
		}else if (orderId.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_42.toString()))) {
			payment.setVoucherid(orderId.substring(0,orderId.length()-3));
			payment.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_42);
		}else if (orderId.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_43.toString()))) {
			payment.setVoucherid(orderId.substring(0,orderId.length()-3));
			payment.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_43);
		}else if (orderId.endsWith("-".concat(Constant.CONSTANTS_PAY_ACTION_ID_51.toString()))) {
			payment.setVoucherid(orderId.substring(0,orderId.length()-3));
			payment.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_51);
		}else{
			payment.setVoucherid(orderId);
			payment.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_11);
		}
		
		int execue=ePayCashPaymentService.insert(payment);
		
		logger.info("json LOG :"+JSONArray.toJSONString(payment));
		
		logger.info("execue num :"+execue);
		if (execue==1) {
			return payment.getPaycashid();
		}else{
			return null;
		}
		
	}
	
	
	
	/**
	 * 	 日志更新
	 *   支付成功
	 * @param ePayCashPayment
	 * @return payCashId
	 */
	public void updatePayCashPaymentLog(String outTradeNo,EPayCashPayment payment) {
		
		logger.info("ePayCashPayment日志开始");
		IEPayCashPaymentService ePayCashPaymentService =	SpringContextUtil.getBean("ePayCashPaymentService");
		logger.info("ePayCashPaymentService获取server");
		payment.setPaycashDate(DateUtils.now());
		String[] strs = outTradeNo.split("-");
		payment.setPaycashid(Long.valueOf(strs[0]));
		//payment.setVoucherid(strs[1]);
		payment.setPaystepid(Constant.CONSTANTS_PAY_STEP_3);
		payment.setPaycashSign(Constant.CONSTANTS_IS_PAYMENT_TRUE);
		payment.setUpdateUserid(PropertiesUtil.getLong("defalutUser",2));
		
		ePayCashPaymentService.updateByPayCashIDSelective(payment);
		
	}
	
	
	/**
	 * 更新nonceStr
	 * @param ePayCashPayment
	 * @return payCashId
	 */
	public void updateWXNonceStrPaymentLog(Long  payCashId,String nonceStr) {
		
		logger.info("ePayCashPayment日志开始");
		IEPayCashPaymentService ePayCashPaymentService =SpringContextUtil.getBean("ePayCashPaymentService");
		logger.info("ePayCashPaymentService获取server");
		EPayCashPayment ePayCashPaymentForUpdate = new EPayCashPayment();
		ePayCashPaymentForUpdate.setPaycashid(payCashId);
		ePayCashPaymentForUpdate.setComment(nonceStr);
		
		ePayCashPaymentService.updateByPayCashIDSelective(ePayCashPaymentForUpdate);
	}
	
	
	
	/**
	 * 关闭过期的订单
	 * @param ePayCashPayment
	 */
	public Long cleanExpiredPayment(String  orderId ,Short flag) throws Exception{
		
		logger.info("ePayCashPayment日志开始");
		IEPayCashPaymentService ePayCashPaymentService =	SpringContextUtil.getBean("ePayCashPaymentService");
		logger.info("ePayCashPaymentService获取server");
		
		String[] strs = orderId.split("-");
		List<EPayCashPayment> list = new ArrayList<EPayCashPayment>();
		//普通订单
		if (strs.length==1) {
			list=ePayCashPaymentService.selectByOrderId(Long.valueOf(orderId));
		}else if(strs.length==2){
			//充值 买卡订单
			EPayCashPaymentExample example = new EPayCashPaymentExample();
			example.setVoucherid(strs[0]);
			example.setSourceid(Integer.valueOf(  strs[1]));
			example.setRunStatus("1");
			
			list= ePayCashPaymentService.selectByExample(example);
			
		}else{
			
			return null;
		}
		
		for (int i = 0; i < list.size(); i++) {
			EPayCashPayment ePayCashPayment = list.get(i);
			
			int paycashTypeid = ePayCashPayment.getPaycashTypeid().intValue();
			
			//微信取消订单
			if(paycashTypeid==Constant.CONSTANTS_PAYMENT_WEIXIN){
				
			    IWXPayService wXPayService = SpringContextUtil.getBean("wXPayService");
				
				CloseOrderReqData closeOrderReqData = new CloseOrderReqData(ePayCashPayment.getPaycashIdno(), ePayCashPayment.getComment());
			    wXPayService.closeOrder(closeOrderReqData);
			
			 //支付宝取消订单
			}else if(paycashTypeid==Constant.CONSTANTS_PAYMENT_ALIPAY){
			 IAlipayService alipayService = SpringContextUtil.getBean("alipayService");
			 alipayService.close(null, ePayCashPayment.getPaycashIdno());
			}	
			
			  EPayCashPayment ePayCashPaymentForUpdate = new EPayCashPayment();
			  ePayCashPaymentForUpdate.setPaycashid(ePayCashPayment.getPaycashid());
			  ePayCashPaymentForUpdate.setRunStatus(String.valueOf(Constant.CONSTANTS_PAY_STATUS_CLOSE));
			  ePayCashPaymentForUpdate.setUpdateDate(DateUtils.now());
			  ePayCashPaymentService.updateByPayCashIDSelective(ePayCashPaymentForUpdate);
		}
		return  insertPayCashPaymentLog(orderId, flag, ePayCashPaymentService);
	}
	
	
	
	/**
	 * 关闭过期的订单
	 * @param ePayCashPayment
	 */
	public boolean cancelPayment(String  orderId ) throws Exception{
		
		logger.info("ePayCashPayment日志开始");
		IEPayCashPaymentService ePayCashPaymentService =	SpringContextUtil.getBean("ePayCashPaymentService");
		logger.info("ePayCashPaymentService获取server");
		
		//List<EPayCashPayment> list = ePayCashPaymentService.selectByOrderId(orderId);
		String[] strs = orderId.split("-");
		List<EPayCashPayment> list = new ArrayList<EPayCashPayment>();
		//普通订单
		if (strs.length==2) {
			list=ePayCashPaymentService.selectByOrderId(Long.valueOf(strs[1]));
		}else if(strs.length==3){
			//充值 买卡订单
			EPayCashPaymentExample example = new EPayCashPaymentExample();
			example.setVoucherid(strs[1]);
			example.setSourceid(Integer.valueOf(  strs[2]));
			example.setRunStatus("1");
			
			list= ePayCashPaymentService.selectByExample(example);
			
		}else{
			
			return true;
		}
			
		for (int i = 0; i < list.size(); i++) {
			EPayCashPayment ePayCashPayment = list.get(i);
			
			int paycashTypeid = ePayCashPayment.getPaycashTypeid().intValue();
			
			//微信取消订单
			if(paycashTypeid==Constant.CONSTANTS_PAYMENT_WEIXIN){
				
			    IWXPayService wXPayService = SpringContextUtil.getBean("wXPayService");
				
				int fee = ePayCashPayment.getPaycashTotal().multiply(new BigDecimal(100)).intValue();
				RefundReqData refundReqData = new RefundReqData(
						ePayCashPayment.getBankCashIdno(), 
						ePayCashPayment.getPaycashIdno(), null,
						ePayCashPayment.getPaycashIdno(),
						fee,fee, null, null);
				RefundResData refundResData = wXPayService.refund(refundReqData);
				String resultCode = refundResData.getResult_code();
				
				//SUCCESS 微信取消成功
				if (StringUtils.isNotBlank(resultCode)&&resultCode.equals("SUCCESS")) {
					
				}else{
					return false;
				}
				
				
			
			//支付宝取消订单
			}else if(paycashTypeid==Constant.CONSTANTS_PAYMENT_ALIPAY){
			 IAlipayService alipayService = SpringContextUtil.getBean("alipayService");
			 AlipayTradeRefundResponse  AlipayTradeRefundResponse =
			 alipayService.refund(ePayCashPayment.getPaycashIdno(),
					 ePayCashPayment.getBankCashIdno(), 
					 String.valueOf(ePayCashPayment.getPaycashTotal().setScale(2)),
										null, null, null, null, null);
			 
			 	String resultCode = AlipayTradeRefundResponse.getCode();
				//10000 支付宝取消接口
				if (StringUtils.isNotBlank(resultCode)&&resultCode.equals("10000")) {
					
				}else{
					return false;
				}
			 
			}
			
			
			//更新回调日志表
			EPayCashPayment ePayCashPaymentForUpdate = new EPayCashPayment();
			ePayCashPaymentForUpdate.setPaycashid(ePayCashPayment.getPaycashid());
			ePayCashPaymentForUpdate.setPaycashIdno(ePayCashPayment.getPaycashIdno()+"R");
			ePayCashPaymentForUpdate.setPaycashSign(Constant.CONSTANTS_IS_PAYMENT_CANCEL);
			ePayCashPaymentService.updateByPayCashIDSelective(ePayCashPaymentForUpdate);
		}
		return true;
	}
}
